package cn.wildfire.chat.kit.setting;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.view.View;
import android.widget.TextView;

import com.kyleduo.switchbutton.SwitchButton;
import com.sourcemuch.im.caiba.CaiBaChatApp;
import com.sourcemuch.im.caiba.ExtendSplashActivity;
import com.sourcemuch.im.caiba.InterfaceReceiversHub;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.SuperService;

import butterknife.BindView;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.ui.CustomAppUIDialog;
import cn.wildfire.chat.app.extendsion.ui.TipDialog;
import cn.wildfire.chat.app.extendsion.utils.NotificationUtils;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.app.main.PrivacyPolicyActiviy;
import cn.wildfire.chat.app.main.UserAgrementActiviy;
import cn.wildfire.chat.kit.ChatManagerHolder;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfire.chat.kit.user.BlackListActivity;
import cn.wildfirechat.model.Conversation;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;

public class SettingActivity extends WfcBaseActivity {


    @BindView(R2.id.exitOptionItemView)
    TextView exitOptionItemView;
    @BindView(R2.id.newsSwitchButton)
    SwitchButton newsSwitchButton;
    @BindView(R2.id.versionTextView)
    TextView versionTextView;

    protected UserInfo loginUserInfo;

    @Override
    protected int contentLayout() {
        return R.layout.setting_activity;
    }

    @SuppressLint({"ApplySharedPref", "StaticFieldLeak"})
    @OnClick(R2.id.exitOptionItemView)
    void exit() {
        try {
            TipDialog.showCustomDialog(this, getString(R.string.wendy_title), getString(R.string.confirm_logout_msg)
                    , new String[]{getString(R.string.confirm), getString(R.string.cancle_but)}, CustomAppUIDialog.TYPE_CONFIRM_CANCLE
                    , true, 2, false, new TipDialog.OnMsgTipDialogListener() {
                        @Override
                        public void then(boolean confirm, boolean outtouch) {
                            if (confirm) {
                                new AsyncTask<String, Integer, String>() {
                                    @Override
                                    protected String doInBackground(String... strings) {
                                        try {
                                            // 解除小米推送绑定
                                            if (loginUserInfo != null && !TextUtils.isTextEmpty(loginUserInfo.mobile)) {
                                                InterfaceReceiversHub.unsetMiPushAccount(CaiBaChatApp.getContext(), loginUserInfo.uid);
                                            }
                                            // 修改退出登入后，登入另一个账号，应用信息依然是上一个账号信息。
                                            SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
                                            sp.edit().clear().commit(); // apply与commit的区别，commit即时保存
                                            // 更换至删除会话信息后再进行IM服务断开连接操作
                                            ChatManagerHolder.gChatManager.disconnect(true);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        return null;
                                    }

                                    @Override
                                    protected void onPostExecute(String s) {
                                        super.onPostExecute(s);
                                        try {
                                            // 清空管理员的会话内容，用于保证下次登入信息只显示一条
                                            Conversation conversation = new Conversation(Conversation.ConversationType.Single, "admin");
                                            ChatManager.Instance().clearMessages(conversation);
                                            ChatManager.Instance().removeConversation(conversation, true);
                                            // 关闭守护服务
                                            stopService(new Intent(SettingActivity.this, SuperService.class));
                                            // 回程序登入界面
                                            Intent intent = new Intent(SettingActivity.this, ExtendSplashActivity.class);
                                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                            intent.putExtra("fromLogout", true);
                                            startActivity(intent);
                                            finish();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }.execute();
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        setNotifyStatus();
    }

    @Override
    protected void afterViews() {
        super.afterViews();
        newsSwitchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NotificationUtils.gotoNotificationSetting(SettingActivity.this, 101);
            }
        });
        versionTextView.setText(getString(R.string.current_versioncode) + ":" + packageName(this));
        loginUserInfo = ChatManager.Instance().getUserInfo(ChatManager.Instance().getUserId(), false);
    }

    public String packageName(Context context) {
        PackageManager manager = context.getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }

    /**
     * 设置通知开关显示
     */
    private void setNotifyStatus() {
        boolean areNotificationsEnabled = NotificationUtils.isNotificationEnabled(this);
        newsSwitchButton.setCheckedNoEvent(areNotificationsEnabled);
    }


    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        setToolbarOrReplaceType(true, 3);
        setReplaceTitle(getTitle().toString(), -1);
        setSearchLayoutVisibility(false);
    }

    @OnClick({R2.id.rl_blacklist, R2.id.rl_user_agreement, R2.id.rl_privacy_policy})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.rl_blacklist) {
            Intent intentBlackList = new Intent(SettingActivity.this, BlackListActivity.class);
            startActivity(intentBlackList);
        } else if (id == R.id.rl_user_agreement) {
            Intent intent = new Intent(SettingActivity.this, UserAgrementActiviy.class);
            startActivity(intent);
        } else if (id == R.id.rl_privacy_policy) {
            Intent intentPrivacyPolicy = new Intent(SettingActivity.this, PrivacyPolicyActiviy.class);
            startActivity(intentPrivacyPolicy);
        }
    }
}
